package com.navinfo.tripanalysis.offline.service.impl;

import com.navinfo.tripanalysis.offline.service.ConfigFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

import java.io.*;
import java.util.Map;
import java.util.Properties;

/**
 * @author 沈东生
 */
public class ConfigFileServiceYamlImpl implements ConfigFileService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFileServiceYamlImpl.class);

    private InputStream inputStream;

    public InputStream getInputStream() {
        return inputStream;
    }

    public ConfigFileService setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
        return this;
    }

    @Override
    public Properties load() {
        Properties props = new Properties();
        InputStream in = getInputStream();
        if(null != in){
            try {
                Yaml yaml = new Yaml(new SafeConstructor());
                Map<Object, Object> ret = yaml.load(new InputStreamReader(in));
                if (null != ret) {
                    for (Map.Entry<Object, Object> en : ret.entrySet()) {
                        props.setProperty(en.getKey().toString(), en.getValue().toString());
                    }
                }
            } catch (Exception ex) {
                LOGGER.error("加载配置文件失败...", ex);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            }
        }
        return props;
    }
}
